<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <!-- <template slot="menuLeft">
        <el-button
          type="primary"
          size="small"
          icon="el-icon-delete"
          v-if="permission.allowance_delete"
          @click="handleDelete"
          >删 除
        </el-button>
      </template> -->
      <template slot="info">
        <div>详情</div>
      </template>
      <template slot="infoForm" slot-scope="{ row, index }">
        <avue-crud
          :option="options"
          :data="info"
          :before-open="beforeOpens"
          v-model="form"
          ref="cruds"
        >
          <template slot="gear" slot-scope="{ row }">
            <div>{{ row.gear ? row.gear : "/" }}</div>
          </template>
          <template slot="amount" slot-scope="{ row }">
            <div>
              <div v-if="row.subsidy == 3">/</div>
              <div v-else>
                <el-input
                  clearable
                  v-model="row.amount"
                  placeholder="请输入补贴金额"
                >
                </el-input>
              </div>
            </div>
          </template>
        </avue-crud>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
} from "@/api/configure/allowance";
import { mapGetters } from "vuex";
import { getList as getLevelList } from "@/api/configure/level";

export default {
  data() {
    return {
      info: [],
      options: {
        align: "center",
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        selection: false,
        menu: false,
        header: false,
        addBtn: false,
        cellBtn: true,
        menuWidth: 250,
        column: [
          {
            label: "等级",
            prop: "levelName",
          },
          // {
          //   label: "档位数",
          //   prop: "gear",
          //   slot: true,
          // },
          {
            label: "补贴标准",
            prop: "subsidy",
            type: "select",
            dicUrl: "/api/fine-system/dict/dictionary?code=allowance_standards",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "number",
            rules: [
              {
                required: true,
                message: "请选择补贴标准",
                trigger: "blur",
              },
            ],
          },
          {
            label: "补贴金额",
            prop: "amount",
            slot: true,
            rules: [
              {
                required: true,
                message: "请输入补贴金额",
                trigger: "change",
              },
              {
                pattern: /^(([0-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
                message: "补贴金额必须大于0且只能保留两位小数",
                trigger: "change",
              },
            ],
          },
        ],
      },
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      data: [],
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.allowance_add, false),
        viewBtn: this.vaildData(this.permission.allowance_view, false),
        delBtn: this.vaildData(this.permission.allowance_delete, false),
        editBtn: this.vaildData(this.permission.allowance_edit, false),
      };
    },
    option() {
      return {
        align: "center",
        height: "auto",
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        selection: true,
        addBtn: false,
        dialogClickModal: false,
        searchMenuSpan: 6,
        delBtn: false,
        editBtnText: "信息维护",
        column: [
          {
            label: "补助类型",
            prop: "subsidyType",
            type: "select",
            dicUrl: "/api/fine-system/dict/dictionary?code=subsidy_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            search: true,
            searchSpan: 4,
            dataType: "number",
            rules: [
              {
                required: true,
                message: "请选择补助类型",
                trigger: "blur",
              },
            ],
          },

          {
            label: "补贴试用",
            prop: "subsidyScope",
            type: "select",
            dicUrl: "/api/fine-system/dict/dictionary?code=dept_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            showColumn: false,
            search: true,
            searchSpan: 4,
            dataType: "number",
            rules: [
              {
                required: true,
                message: "请选择补贴试用",
                trigger: "blur",
              },
            ],
          },
          {
            label: "补贴名称",
            prop: "name",
            search: true,
            searchSpan: 4,
            rules: [
              {
                required: true,
                message: "请输入补贴名称",
                trigger: "blur",
              },
            ],
          },
          {
            label: "补贴标准",
            prop: "subsidyStandard",
            type: "select",
            dicUrl: "/api/fine-system/dict/dictionary?code=allowance_standards",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            search: true,
            searchSpan: 4,
            dataType: "number",
            rules: [
              {
                required: true,
                message: "请选择补贴标准",
                trigger: "blur",
              },
            ],
          },
          // {
          //   label: "补助地区",
          //   prop: "subsidyScope",
          //   rules: [
          //     {
          //       required: true,
          //       message: "请输入补助地区",
          //       trigger: "blur",
          //     },
          //   ],
          // },
          {
            label: "补贴金额",
            prop: "info",
            slot: true,
            formslot: true,
            addDisplay: this.form.subsidyStandard ? true : false,
            editDisplay: this.form.subsidyStandard ? true : false,
            span: 24,
            // children: {
            //   align: "center",
            //   addBtn: false,
            //   delBtn: false,
            //   cellBtn: true,
            //   headerAlign: "center",
            //   column: [
            //     {
            //       label: "等级",
            //       prop: "levelName",
            //     },
            //     {
            //       label: "档位数",
            //       prop: "gear",
            //       slot: true,
            //     },
            //     {
            //       label: "补贴标准",
            //       prop: "subsidyStandard",
            //       type: "select",
            //       dicUrl:
            //         "/api/fine-system/dict/dictionary?code=allowance_standards",
            //       props: {
            //         label: "dictValue",
            //         value: "dictKey",
            //       },
            //       dataType: "number",
            //       rules: [
            //         {
            //           required: true,
            //           message: "请选择补贴标准",
            //           trigger: "blur",
            //         },
            //       ],
            //     },
            //     {
            //       label: "补贴金额",
            //       prop: "amount",
            //       rules: [
            //         {
            //           required: true,
            //           message: "请输入补贴金额",
            //           trigger: "blur",
            //         },
            //         {
            //           pattern: /^(([0-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
            //           message: "补贴金额必须大于0且只能保留两位小数",
            //           trigger: "blur",
            //         },
            //       ],
            //     },
            //   ],
            // },
            // rules: [
            //   {
            //     required: true,
            //     message: "请输入补贴金额",
            //     trigger: "blur",
            //   },
            // ],
          },
        ],
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  watch: {
    "form.subsidyStandard": {
      handler(val) {
        if (!val) return;
        let arr = [];
        switch (val) {
          case 1:
            let obj1 = {
              levelName: "全部",
              gear: "",
              subsidy: 1,
              amount: "",
            };
            arr.push(obj1);
            break;
          case 2:
            getLevelList(1, 1000000).then((res) => {
              let data = res.data.data.records;
              data.forEach((ele) => {
                let obj = {
                  levelName: ele.levelName,
                  gear: ele.num,
                  subsidy: 2,
                  amount: "",
                };
                arr.push(obj);
              });
            });
            break;
          case 3:
            let obj3 = {
              levelName: "全部",
              gear: "",
              subsidy: 3,
              amount: "",
            };
            arr.push(obj3);
            break;
        }
        this.info = arr;
      },
    },
  },
  methods: {
    rowSave(row, done, loading) {
      row.info = this.info;
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      row.info = this.info;
      // if (row.subsidyStandard != 3) {
      //   for (let i = 0; i < row.info.length; i++) {
      //     if (!row.info[i].amount) {
      //       return this.$message({
      //         type: "error",
      //         message: `第${index + 1}行补贴金额不能为空`,
      //       });
      //     } else if (
      //       !/^(([0-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/.test(row.info[i].amount)
      //     ) {
      //       return this.$message({
      //         type: "error",
      //         message: `第${index + 1}行补贴金额必须大于0且只能保留两位小数`,
      //       });
      //     }
      //   }
      // }
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
          // if(res.data.data.)
          this.info = res.data.data.info;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
  },
};
</script>

<style></style>
